module.exports = app => {
  const express = require('express')
  const Specialty = require('../../models/Specialty')
  const Department = require(`../../models/Department`)
  const Teacher = require('../../models/Teacher')
  const User = require('../../models/User')
  const Student = require('../../models/Student')
  const Grade = require('../../models/Grade')
  const College = require('../../models/College')
  const Class = require('../../models/Class')
  const Course = require('../../models/Course')
  const AdminUser = require("../../models/AdminUser")
  const auth = require("../../middleware/auth")

  /*------------这里是获取分页列表的公共接口部分------------*/
  const lrouter = express.Router({
    mergeParams: true
  })

  lrouter.get('/', (req, res) => {
    let limit = parseInt(req.query.size) || 10; //分页参数
    let currentPage = parseInt(req.query.page) || 1; //当前页码
    let params = req.query;
    const queryOptions = {} //要关联其他表的时候的配置
    if (req.Model.modelName === "Teacher") {
      queryOptions.populate = 'department'
    }
    if (req.Model.modelName === "Class") {
      queryOptions.populate = 'superior'
    }
    if (req.Model.modelName == "Student") {
      queryOptions.populate = [{
        path: "class",
        select: ["_id", "name"]
      }, {
        path: "specialty",
        select: ["_id", "name"]
      }]
    }
    if (req.Model.modelName == "Course") {
      queryOptions.populate = [{
        path: "teacher",
        select: ["_id", "name"]
      }, {
        path: 'class',
        select: ['_id', "name"]
      }]
    }
    if (req.Model.modelName == "Grade") {
      queryOptions.populate = [{
        path: "course",
        select: ["_id", "coursename", 'nid']
      }, {
        path: "student",
        select: ["_id", "name", "nid"]
      }]
    }
    if (currentPage < 1) {
      currentPage = 1;
    }
    if (limit < 1) {
      limit = 1;
    }
    queryOptions.limit = limit;
    queryOptions.skip = (currentPage - 1) * limit;
    req.Model.find({}, (err, ress) => {
      if (err) return res.json({
        success: false,
        message: err
      });
      let all = ress.length;
      req.Model.find().setOptions(queryOptions).exec(async (err, doc) => {
        if (err) {
          return res.json({
            success: false,
            message: err
          });
        }
        if (req.Model.modelName == 'User') {
          let returnDoc = []
          for (let i = 0; i < doc.length; i++) {
            let docs = ''
            if (doc[i].identity == 0) {
              docs = await Student.findById(doc[i].bindId)
            } else if (doc[i].identity == 1 || doc[i].identity == 2) {
              docs = await Teacher.findById(doc[i].bindId);
            }
            let temp = {
              name: docs.name,
              username: doc[i].username,
              username: doc[i].username,
              bindId: doc[i].bindId,
              password: doc[i].password,
              identity: doc[i].identity,
              _id: doc[i]._id
            }
            returnDoc.push(temp)
          }
          return res.json({
            success: true,
            message: "请求成功",
            counts: all,
            list: returnDoc
          })
        } else {
          return res.json({
            success: true,
            message: "请求成功",
            counts: all,
            list: doc
          })
        }
      })
    })
  })

  app.use('/admin/api/list/:resource', auth(), async (req, res, next) => {
    req.Model = require(`../../models/${req.params.resource}`)
    next()
  }, lrouter)

  /**-----------查询列表的接口----------------------------------**/
  let slrouter = express.Router({
    mergeParams: true
  })

  slrouter.get('/', async (req, res) => {
    let limit = parseInt(req.query.size) || 10; //分页参数
    let currentPage = parseInt(req.query.page) || 1; //当前页码
    let params = req.query;
    let mp = {}

    const queryOptions = {} //要关联其他表的时候的配置
    if (req.Model.modelName === "Teacher") {
      queryOptions.populate = 'department'
    }
    if (req.Model.modelName === "Class") {
      queryOptions.populate = 'superior'
    }
    if (req.Model.modelName == "Student") {
      queryOptions.populate = [{
        path: "class",
        select: ["_id", "name"]
      }, {
        path: "specialty",
        select: ["_id", "name"]
      }]
    }
    if (req.Model.modelName == "Course") {
      queryOptions.populate = [{
        path: "teacher",
        select: ["_id", "name"]
      }, {
        path: 'class',
        select: ['_id', "name"]
      }]
    }
    if (req.Model.modelName == "Grade") {
      queryOptions.populate = [{
        path: "course",
        select: ["_id", "coursename", 'nid']
      }, {
        path: "student",
        select: ["_id", "name", "nid"]
      }]
    }
    if (currentPage < 1) {
      currentPage = 1;
    }
    if (limit < 1) {
      limit = 1;
    }
    queryOptions.limit = limit;
    queryOptions.skip = (currentPage - 1) * limit;
    for (let i in params) {
      if (params[i] !== undefined && i != 'size' && i != 'page' && params[i] && params[i] != "''" && i != "teacherNid" && i != "className" && i != 'courseXN' && i != 'courseXq' && i != 'courseNid' && i != 'studentNid') {
        if(i=="superior"||(req.Model.modelName=="Student"&&(i=="specialty"||i=="class"))||(req.Model.modelName=="Teacher"&&i=="department")){
          mp[i]=params[i]
          continue
        }
        let reg = new RegExp(params[i], 'i')
        mp[i] = {
          $regex: reg
        }
        //  params[i]
      }
    }

    if (req.Model.modelName == "Course") {
      if (params['className']) {
        let classRes = await Class.findOne({
          'name': params['className']
        })
        if (classRes) {
          mp.class = classRes._id
        } else {
          return res.json({
            success: true,
            list: [],
            counts: 0
          })
        }
      }

      if (params['teacherNid']) {
        let teacherRes = await Teacher.findOne({
          nid: params['teacherNid']
        });
        if (teacherRes) {
          mp.teacher = teacherRes._id
        } else {
          return res.json({
            success: true,
            list: [],
            counts: 0
          })
        }
      }
    }
    // console.log({...mp})

    req.Model.find({
      ...mp
    }, (err, ress) => {
      if (err) {
        // console.log(`err=>${err}`)
        return res.json({
          success: false,
          message: 1
        });
      }
      let all = ress.length;
      req.Model.find({
        ...mp
      }).setOptions(queryOptions).exec(async (err, doc) => {
        if (err) {
          return res.json({
            success: false,
            message: err
          });
        }
        if (req.Model.modelName == 'User') {
          let returnDoc = []
          for (let i = 0; i < doc.length; i++) {
            let docs = ''
            if (doc[i].identity == 0) {
              docs = await Student.findById(doc[i].bindId)
            } else if (doc[i].identity == 1 || doc[i].identity == 2) {
              docs = await Teacher.findById(doc[i].bindId);
            }
            let temp = {
              name: docs.name,
              username: doc[i].username,
              username: doc[i].username,
              bindId: doc[i].bindId,
              password: doc[i].password,
              identity: doc[i].identity,
              _id: doc[i]._id
            }
            returnDoc.push(temp)
          }
          return res.json({
            success: true,
            message: "请求成功",
            counts: all,
            list: returnDoc
          })
        } else {
          return res.json({
            success: true,
            message: "请求成功",
            counts: all,
            list: doc
          })
        }
      })
    })
  })

  app.use('/admin/api/searchList/:resource', auth(), async (req, res, next) => {
    req.Model = require(`../../models/${req.params.resource}`)
    next()
  }, slrouter)

  app.get('/admin/api/searchAPI/Grade', auth(), async (req, res) => {
    let limit = parseInt(req.query.size) || 10; //分页参数
    let currentPage = parseInt(req.query.page) || 1; //当前页码
    let params = req.query;
    let mp = {} //这个是Course的mp
    let gmp = {} //这个是Grade的mp
    const queryOptions = {} //要关联其他表的时候的配置
    queryOptions.populate = [{
      path: "course",
      select: ["_id", "coursename", 'nid']
    }, {
      path: "student",
      select: ["_id", "name", "nid"]
    }]
    queryOptions.limit = limit;
    queryOptions.skip = (currentPage - 1) * limit;

    //如果查询时候，有带教师编号
    if (params['teacherNid']) {
      //则开始查询
      let teacherRes = await Teacher.findOne({
        nid: params['teacherNid']
      });
      // console.log(teacherRes);

      //如果查询有结果，则在course查询mp中插入
      if (teacherRes) {
        mp.teacher = teacherRes._id
      } else {
        //没有，则返回空，以示错误
        return res.json({
          success: true,
          list: [],
          counts: 0
        })
      }
    }

    if (params['className']) {
      let classRes = await Class.findOne({
        'name': params['className']
      });
      if (classRes) {
        let studentIdList = await Student.find({
          class: classRes._id
        }, {
          _id: 1
        })
        // studentMp.class = classRes._id; 
        gmp.student = {
          $in: studentIdList
        }
      } else {
        return res.json({
          success: true,
          list: [],
          counts: 0
        })
      }
    }
    if (params['courseNid']) {
      mp.nid = params['courseNid']
    }
    if (params['courseXn']) {
      mp.year = params['courseXn']
      // console.log(mp.year);

    }
    if (params['courseXq']) {
      mp.xq = params['courseXq']
    }
    let courseList = await Course.find({
      ...mp
    }, {
      _id: 1
    })


    if (courseList.length > 0) {
      gmp.course = {
        $in: courseList
      }
    } else if (JSON.stringify(mp) != '{}') {
      return res.json({
        success: true,
        list: [],
        counts: 0
      })
    }
    if (params['studentNid']) {

      let studentRes = await Student.findOne({
        nid: params['studentNid']
      })
      if (studentRes) {
        gmp.student = studentRes._id;
        // console.log(studentRes);

      } else {
        return res.json({
          success: true,
          list: [],
          counts: 0
        })
      }
    }
    Grade.find({
      ...gmp
    }, async (error, allDocs) => {
      if (error) {
        return res.json({
          success: false,
          message: error
        })
      }
      let all = allDocs.length;
      Grade.find({
        ...gmp
      }).setOptions(queryOptions).exec(async (err, doc) => {

        if (err) {
          return res.json(err)
        }
        return res.send({
          success: true,
          list: doc,
          counts: all
        })
      })
    })

  })
}